package com.sky.controller.notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.WeChatProperties;
import com.sky.service.OrderService;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 支付回调相关接口
 *
 * @author normal
 * @date 2025年03月01日 下午3:20
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/notify")
public class PaymentNotifyController {

    /**
     *  订单处理
     */
    private OrderService orderService;

    /**
     *  微信相关属性
     */
    private WeChatProperties weChatProperties;


    @RequestMapping("/paySuccess")
    public void paySuccessNotify(HttpServletRequest request, HttpServletResponse response,String number) throws IOException {
        // todo： 相关接口无法申请无法对接,直接就当支付成功
        // 读取数据
//        String data = readData(request);
//        log.info("支付成功回调:{}", data);

        // 数据解密
//        String plainText = decryptData(data);
//        log.info("解密后的文本:{}", plainText);

        // 修改当前订单状态为支付
        log.info("订单支付成功,订单号为{}",number);
        orderService.paySuccess(number);




        // 给微信响应..


    }

    /**
     * 数据解密
     *
     * @param body
     * @return
     * @throws Exception
     */
    private String decryptData(String body) throws Exception {
        JSONObject resultObject = JSON.parseObject(body);
        JSONObject resource = resultObject.getJSONObject("resource");
        String ciphertext = resource.getString("ciphertext");
        String nonce = resource.getString("nonce");
        String associatedData = resource.getString("associated_data");
        AesUtil aesUtil = new AesUtil(weChatProperties.getApiV3Key().getBytes(StandardCharsets.UTF_8));
        //密文解密
        String plainText = aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8),
                nonce.getBytes(StandardCharsets.UTF_8),
                ciphertext);

        return plainText;
    }

    /**
     * 读取数据
     * @param request
     * @return
     */
    private String readData(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder result = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    }


}
